package cn.demoxy.service.impl;

import cn.demoxy.mapper.DemoMenuMapper;
import cn.demoxy.model.dto.DemoMenuDTO;
import cn.demoxy.model.entity.DemoMenu;
import cn.demoxy.service.IDemoMenuService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @auther demo
 * @date 2022/5/20 9:35
 * 菜单表业务实现
 */
@Service
public class DemoMenuServiceImpl extends ServiceImpl<DemoMenuMapper, DemoMenu> implements IDemoMenuService {


    @Override
    public List<DemoMenu> getMenuByRoleId(String roleId) {
            List<DemoMenu> menuList = baseMapper.getMenuByRoleId(roleId);
        return menuList;

    }

    @Override
    public List<DemoMenu> findAllMenu() {
        //获取父级菜单
        List<DemoMenu> parentMenu = baseMapper.selectList(new QueryWrapper<DemoMenu>().eq("parent_id",'0').orderByDesc("sort"));
        if (parentMenu != null && parentMenu.size() > 0) {
            parentMenu.forEach(this::findAllChild);
        }
        return parentMenu;
    }

    @Override
    public boolean deleteMenuById(String id) {
        baseMapper.deleteById(id);
        baseMapper.delete(new QueryWrapper<DemoMenu>().eq("parent_id",id));
        return true;
    }

    /**
     *首次进入这个方法时，查出的是二级节点列表
     *递归调用时，就能依次查出三、四、五等等级别的节点列表，
     *递归能实现不同节点级别的无限调用,这个层次不易太深，否则有性能问题
     * @param Menu
     *
     */
    private void findAllChild(DemoMenu Menu) {
        List<DemoMenu> childrenMenu = baseMapper.selectList(new QueryWrapper<DemoMenu>()
                .eq("parent_id", Menu.getId()).orderByDesc("sort"));
        Menu.setChildrenMenus(childrenMenu);
        if (childrenMenu != null && childrenMenu.size() > 0) {
            childrenMenu.forEach(this::findAllChild);
        }
    }
}
